﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

using System.Data.SqlClient;
using System.Web.Configuration;
using System.Security.Cryptography;
using System.Text;

namespace HiViLicenseManage
{
	public partial class Login : System.Web.UI.Page
	{
		protected void Page_Load(object sender, EventArgs e)
		{
		}

		protected void cLogin_Authenticate(object sender, AuthenticateEventArgs e)
		{
			try
			{
				if (CheckLogin(cLogin.UserName, cLogin.Password) == true)
				{
					FormsAuthentication.RedirectFromLoginPage(cLogin.UserName.ToUpper(), cLogin.RememberMeSet);
					e.Authenticated = true;
				}
				else
					e.Authenticated = false;
			}
			catch
			{
				Response.Redirect("~/Error.aspx", false);
			}
		}

		private bool CheckLogin(string userid, string pass)
		{
			SqlConnection appConn = new SqlConnection(WebConfigurationManager.ConnectionStrings["appconn"].ConnectionString);
			appConn.Open();
			
			SqlCommand sqlComm = new SqlCommand("SELECT AgentID FROM Agent WHERE UPPER(AgentID) = @AgentID AND Password = @Password AND Status = 'True'", appConn);
			sqlComm.CommandType = CommandType.Text;
			sqlComm.Parameters.Add("@AgentID", SqlDbType.VarChar).Value = userid.ToUpper();
			sqlComm.Parameters.Add("@Password", SqlDbType.VarChar).Value = Enc.Encrypt(pass, userid.ToUpper());
			SqlDataAdapter sqlDA = new SqlDataAdapter();
			sqlDA.SelectCommand = sqlComm;
			DataTable dtAgent = new DataTable();
			sqlDA.Fill(dtAgent);

			appConn.Close();

			if (dtAgent.Rows.Count > 0)
				return true;
			else
				return false;
		}
	}
}
